package com.example.yc23.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.yc23.demo.pojo.Maker;
import com.example.yc23.demo.service.MakerService;
import com.example.yc23.demo.service.OccupationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/admin/maker")
public class MakerController {
    @Autowired
    private MakerService makerService;
    @Autowired
    private OccupationService occupationService;

    @GetMapping("/index")
    public void index(String key,@RequestParam(defaultValue = "1") Integer state ,
                      @RequestParam(defaultValue = "1") Integer pn,
                      @RequestParam(defaultValue ="8" ) Integer ps,Model model){
        QueryWrapper wrapper=null;
        wrapper=new QueryWrapper();
        wrapper.eq("state",state);
        if (key!=null&&!"".equals(key)){
            wrapper.like("name",key);
        }
        Page<Maker> page=new Page<>(pn,ps);
        model.addAttribute("page",makerService.page(page,wrapper));
//        return "admin/maker/index";
    }
    @GetMapping({"/add","/update/{id}"})
    public String add(@PathVariable(required = false) Integer id,Model model){
        model.addAttribute("occuList",occupationService.list());
        if (id!=null){
//            Maker maker=makerService.getById(id);
//            model.addAttribute("maker",maker);
            model.addAttribute("maker",makerService.getById(id));
        }
        return "admin/maker/updateoradd";
    }
    @PostMapping("/updateoradd")
    public String updateoradd(Maker maker, Model model){
        if (makerService.saveOrUpdate(maker)){
            return "redirect:/admin/maker/index";
        }else{
            model.addAttribute("maker",maker);
            model.addAttribute("msg_err","操作失败");
            model.addAttribute("occuList",occupationService.list());
            return "admin/maker/updateoradd";
        }
    }
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable Integer id){
//        makerService.removeById(id);//物理删除
        //逻辑删除
        makerService.updateStateById(id,0);//状态为0表示该数据被删除
        return "redirect:/admin/maker/index";
    }
    @RequestMapping("/recover/{id}")
    public String recover(@PathVariable Integer id){
//        makerService.removeById(id);//物理删除
        //逻辑删除
        makerService.updateStateById(id,1);//状态为0表示该数据被删除
        return "redirect:/admin/maker/index";
    }


}
